import json
import logging
from datetime import datetime

from flask import Flask, jsonify, request, Blueprint, current_app
from APP.models.DangerFuture import DangerFuture
from APP.database import db
import random
# 创建蓝图
danger_future = Blueprint('danger_future', __name__)

logger = logging.getLogger(__name__)
# @danger_future_bp.route('/dangerReport/<int:report_id>', methods=['GET'])
# def get_danger_report(report_id):
#     try:
#         # 查询指定ID的报告
#         report = db.session.get(DangerFuture, report_id)
#
#         if not report:
#             return jsonify({
#                 "message": "Report not found",
#                 "code": 404
#             }), 404
#
#         # 解析现在和预测未来的数据
#         chart_data = json.loads(report.chart_data) if report.chart_data else []
#         report_content = report.report_content
#
#         response_data = {
#             "id": report.id,
#             "chartdata": chart_data,
#             "startdata": report.start_data,
#             "enddata": report.end_data,
#             "mindata": report.min_data,
#             "maxdata": report.max_data,
#             "redangerpaper": report_content
#         }
#
#         return jsonify({
#             "message": "Success",
#             "code": 200,
#             "data": response_data
#         })
#
#     except Exception as e:
#         logger.error(f"获取预测报告失败: {str(e)}")
#         return jsonify({
#             "message": "Internal server error",
#             "code": 500,
#             "error": str(e)
#         }), 500





@danger_future.route('/redangerCharts/<id>', methods=['GET'])
def get_danger_report(id):
    try:

        report = db.session.get(DangerFuture, id)
        report_content = """
                    ### 1. 概览
                    本报告基于模拟数据进行分析，展示时间序列数据的预测趋势。

                    ### 2. 数据概况
                    #### 当前数据 (过去5年)
                    - **特点**：稳定增长，年均增长率约8%

                    #### 预测数据 (未来5年)
                    - **特点**：预计增速提升至12%，市场前景乐观

                    ### 3. 趋势观察
                    - **历史趋势**：呈现稳步上升曲线
                    - **预测趋势**：预期将保持强劲增长势头
                    """

        # 如果不存在则创建模拟数据
        if not report:
            # 生成时间序列（过去5年 + 未来5年）
            base_year = datetime.now().year - 5
            chart_data = [
                             [f"{base_year + i}-01-01", random.randint(10000, 50000), "current"]
                             for i in range(5)
                         ] + [
                             [f"{base_year + 5 + i}-01-01", random.randint(50000, 100000), "forecast"]
                             for i in range(5)
                         ]

            # 生成报告内容


            # 创建并存储新记录
            report = DangerFuture(
                id=id,
                chart_data=json.dumps(chart_data),
                report_content=report_content,
                start_data="过去5年",
                end_data="未来5年",
                min_data=min(d[1] for d in chart_data),
                max_data=max(d[1] for d in chart_data)
            )
            db.session.add(report)
            db.session.commit()
            response_data = {
                        "id": report.id,
                        "chartdata": chart_data,
                        "startdata": report.start_data,
                        "enddata": report.end_data,
                        "mindata": report.min_data,
                        "maxdata": report.max_data,
                        "redangerpaper": report_content
                     }
            return jsonify({
                "message": "Success",
                "code": 200,
                "data": response_data
            })
        else:
            chart_data = json.loads(report.chart_data) if report.chart_data else []
            response_data = {
                "id": report.id,
                "chartdata": chart_data,
                "startdata": report.start_data,
                "enddata": report.end_data,
                "mindata": report.min_data,
                "maxdata": report.max_data,
                "redangerpaper": report_content
            }
            return jsonify({
                "message": "Success",
                "code": 200,
                "data": response_data
            })

    except Exception as e:
        logger.error(f"获取预测报告失败: {str(e)}")
        return jsonify({
            "message": "Internal server error",
            "code": 500,
            "error": str(e)
        }), 500